Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement tui #2

Merged
merged 3 commits into from
Feb 2, 2025
Merged

feat: implement tui #2

merged 3 commits into from
Feb 2, 2025

Conversation

lgalabru
Copy link
Member

@lgalabru lgalabru commented Feb 2, 2025

Summary by CodeRabbit

  • New Features

    • Added shell completion generation, enhancing the CLI user experience.
    • Introduced an interactive terminal interface for monitoring simulation network events with real-time logging and navigation.
    • Provided new command options for debug logging and display control.
  • Refactor

    • Reworked simulation network command handling with a synchronous, multi-threaded approach for improved reliability.
  • Chores

    • Updated dependency configurations and feature settings for a more robust CLI experience.

Copy link

coderabbitai bot commented Feb 2, 2025

Warning

Rate limit exceeded

@lgalabru has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 13 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 375eed9 and e4946af.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • crates/cli/Cargo.toml (1 hunks)
  • crates/cli/src/cli/mod.rs (5 hunks)
  • crates/cli/src/cli/simnet/mod.rs (1 hunks)
  • crates/cli/src/tui/simnet.rs (1 hunks)
  • crates/core/src/rpc/minimal.rs (1 hunks)
  • crates/core/src/simnet/mod.rs (4 hunks)

Walkthrough

This pull request updates dependency management, command handling, and UI features across several modules. Changes include adding and updating dependencies in the CLI package, enhancing the CLI command structure with a completions command, refactoring the simulation network command to use a synchronous multi-threaded approach, and introducing a full terminal user interface for simnet monitoring. Additionally, core module functions now send simulation events via channels and adjust timing and error handling. Minor modifications in macro imports and RPC imports are also included.

Changes

File(s) Change Summary
crates/cli/Cargo.toml Added new dependencies (ansi_term, clap_complete, crossterm, ratatui, chrono); updated clap_generate format and removed it from the cli feature.
crates/cli/src/cli/mod.rs Updated CLI imports; added bin_name to Opts; introduced new Completions command variant and a helper function generate_completion_helpers to generate shell completion scripts.
crates/cli/src/cli/simnet/mod.rs Changed handle_start_simnet_command from async to synchronous with multi-threading; added a channel for SimnetEvent messages and introduced a new helper function log_events for event-driven logging.
crates/cli/src/macros.rs Removed the unused Style import from the ansi_term crate in several macros.
crates/cli/src/main.rs Added a new public module tui.
crates/cli/src/tui/mod.rs Added a new public module simnet.
crates/cli/src/tui/simnet.rs Implemented a complete TUI for simnet using crossterm and ratatui; introduced UI state management, layout rendering functions, and event handling for simulation network data.
crates/core/src/lib.rs Updated start_simnet function signature to accept a Sender<SimnetEvent>, enabling event-based communication.
crates/core/src/rpc/minimal.rs Removed the Error type import from jsonrpc_core, simplifying error handling in RPC methods.
crates/core/src/simnet/mod.rs Introduced a new SimnetEvent enum for simnet event handling; updated the start function to accept a Sender<SimnetEvent>; reduced the DEFAULT_SLOT_TIME and improved error handling and event dispatching within simnet processing.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant CLI as CLI App
    participant GCH as generate_completion_helpers
    participant FS as File System
    U->>CLI: Invoke "completions" command
    CLI->>GCH: Call generate_completion_helpers(cmd)
    GCH->>FS: Write completion script
    FS-->>GCH: Script saved confirmation
    GCH-->>CLI: Return success message
    CLI-->>U: Display completion instructions
Loading
sequenceDiagram
    participant C as CLI Command
    participant H as Simnet Handler
    participant T as Background Thread
    participant Core as Simnet Core
    participant L as Event Logger
    C->>H: Invoke start_simnet command
    H->>T: Spawn background thread with channel (Tx/Rx)
    T->>Core: Run start_simnet(simnet_events_tx)
    Core->>T: Send SimnetEvent messages
    T->>L: Relay events to log_events function
    L-->>C: Log processed events
Loading

Possibly related PRs

  • Fix blocking on async thread and add formatting in CI #1: The changes in the main PR, specifically the modifications to the start_simnet function in crates/core/src/lib.rs, are related to the changes in the retrieved PR where the handle_start_simnet_command function in crates/cli/src/cli/simnet/mod.rs was updated to handle the asynchronous nature of start_simnet. Both PRs involve adjustments to the handling of the start_simnet function, indicating a direct relationship at the code level.

Poem

I'm a hoppy rabbit with code in my ear,
Watching CLI and TUI bring simnet cheer.
Dependencies leap like bunnies in spring,
Commands and events now dance and sing.
Through channels and threads, our code will race—
A joyful, rhythmic, petal-filled chase!
🐰✨ CodeRabbit delights in every trace!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@lgalabru lgalabru marked this pull request as ready for review February 2, 2025 05:12
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (5)
crates/cli/src/cli/simnet/mod.rs (2)

15-18: Consider more graceful fallback instead of forcing process exit.
Currently, if nestable_block_on fails, the thread logs the error, sleeps, and then calls std::process::exit(1). This approach abruptly terminates the entire process, which might hinder debugging or partial recovery scenarios.

Consider returning the error to the main thread or providing a retry mechanism before exiting:

 if let Err(e) = hiro_system_kit::nestable_block_on(future) {
     error!(ctx_cloned.expect_logger(), "{e}");
     std::thread::sleep(std::time::Duration::from_millis(500));
-    std::process::exit(1);
+    // Possibly propagate this error to the main thread or support a retry count:
+    return Err(e);
 }

24-29: Separate the TUI from logging logic more cleanly.
The current code toggles between log_events and tui::simnet::start_app based on cmd.no_tui. Although this works, merging the logic might help unify how events are handled (e.g., common filtering, shared event queue).

crates/core/src/simnet/mod.rs (1)

71-72: Provide additional logs or fallback for server startup failure.
This block forcibly exits the process if the simulation server cannot start. While it may be appropriate, consider logging the cause or providing a fallback mechanism.

crates/cli/src/tui/simnet.rs (2)

158-225: Limit or rotate stored log events to prevent unbounded memory usage.
Currently, the TUI stores incoming events in a VecDeque without an explicit maximum size, which can lead to high memory usage over time if the simulation runs for an extended period.

To mitigate this:

// For example, keep only the latest 10,000 events:
const MAX_EVENTS: usize = 10_000;
if app.events.len() >= MAX_EVENTS {
    app.events.pop_back();
}

211-223: Validate keyboard input.
All key events are assumed to be valid within the TUI, but spurious or unknown keys might appear. Consider a default case for logging unknown keys or ignoring them gracefully.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f5f097e and a7df4db.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • crates/cli/Cargo.toml (1 hunks)
  • crates/cli/src/cli/mod.rs (5 hunks)
  • crates/cli/src/cli/simnet/mod.rs (1 hunks)
  • crates/cli/src/macros.rs (6 hunks)
  • crates/cli/src/main.rs (1 hunks)
  • crates/cli/src/tui/mod.rs (1 hunks)
  • crates/cli/src/tui/simnet.rs (1 hunks)
  • crates/core/src/lib.rs (1 hunks)
  • crates/core/src/rpc/minimal.rs (1 hunks)
  • crates/core/src/simnet/mod.rs (4 hunks)
✅ Files skipped from review due to trivial changes (2)
  • crates/cli/src/tui/mod.rs
  • crates/cli/src/macros.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (15)
crates/cli/src/tui/simnet.rs (1)

185-186: Align with the renamed ErrorLog event.
If you rename the variant in the core simnet enum to ErrorLog, ensure this usage is also updated here.

- SimnetEvent::ErroLog(dt, log) => {
+ SimnetEvent::ErrorLog(dt, log) => {
crates/core/src/lib.rs (2)

14-15: LGTM! Good separation of concerns.

The addition of Sender and SimnetEvent imports indicates a well-designed event-driven architecture for monitoring simnet events.

Also applies to: 19-19


23-27: LGTM! Clean function signature update.

The updated start_simnet signature now accepts an event channel, enabling real-time monitoring of simnet events. This is a good architectural decision that:

  • Decouples the simnet core from UI concerns
  • Enables real-time monitoring
  • Allows for multiple consumers of simnet events
crates/core/src/rpc/minimal.rs (1)

4-4: LGTM! Clean import statement.

Good cleanup of unused Error import while retaining Result.

crates/cli/src/main.rs (1)

8-8: LGTM! Clean module organization.

Good addition of the public tui module, making the TUI functionality accessible to other parts of the application.

crates/cli/src/cli/mod.rs (3)

73-77: LGTM! Good CLI options for simnet.

The new options provide good flexibility:

  • --no-tui for traditional logging output
  • --debug for detailed debugging

80-85: LGTM! Clean shell completion support.

Good use of clap for shell completion generation with case-insensitive shell selection.


117-126: Verify file permissions and path safety.

The completion script generation looks good but needs additional safety checks.

Consider adding these safety improvements:

 fn generate_completion_helpers(cmd: &Completions) -> Result<(), String> {
     let mut app = Opts::command();
     let file_name = cmd.shell.file_name("surfpool");
+    // Ensure the file doesn't exist or is writable
+    if std::path::Path::new(&file_name).exists() {
+        return Err(format!("File {} already exists", file_name));
+    }
     let mut file = File::create(file_name.clone())
         .map_err(|e| format!("unable to create file {}: {}", file_name, e))?;
+    // Set restrictive permissions
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+        file.set_permissions(std::fs::Permissions::from_mode(0o644))
+            .map_err(|e| format!("unable to set file permissions: {}", e))?;
+    }
     clap_complete::generate(cmd.shell, &mut app, "surfpool", &mut file);
     println!("{} {}", green!("Created file"), file_name.clone());
     println!("Check your shell's docs for how to enable completions for surfpool.");
     Ok(())
 }
crates/cli/Cargo.toml (7)

20-20: New Dependency: ansi_term Added
The dependency ansi_term = "0.12.1" has been added to support terminal styling. Please verify that its functionalities complement the new TUI features introduced via ratatui and that there is no redundancy or conflict with other styling libraries.


24-24: Update: Simplified Format for clap_generate Dependency
The clap_generate dependency is now specified using a simple string format "3.0.3" instead of the previous object format. Ensure that downstream references (e.g., in crates/cli/src/cli/mod.rs) are consistent with this change in dependency specification.


25-25: New Dependency: clap_complete Introduced
The addition of clap_complete = "4.5.44" supports enhanced CLI completions. Confirm that the CLI command structure leverages clap_complete appropriately and that this integration aligns with the updated command handling logic.


26-26: New Dependency: crossterm Added for Terminal I/O
The inclusion of crossterm = "0.28.1" provides powerful terminal I/O capabilities which are essential for the new TUI implementation.


27-27: New Dependency: ratatui for Terminal UI
The dependency ratatui = "0.29.0" has been added to support the new terminal user interface functionality. This is central to the TUI improvements outlined in the PR objectives.


28-28: New Dependency: chrono Included for Date/Time Functions
Adding chrono = "0.4" enriches the package with robust date and time handling. This will be useful for logging or event timestamping in the TUI and other modules.


32-32: Feature Update: Adjusted CLI Feature Configuration
The cli feature has been updated to remove the dependency on clap_generate, now listing only ["clap", "toml", "ctrlc", "hiro-system-kit/log"]. Ensure that any CLI code sections and documentation reflect this modified feature configuration.

Comment on lines 56 to 57
SimnetEvent::ErroLog(_, log) => {
error!(ctx.expect_logger(), "{} ", log);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Rename ErroLog variant for consistency.
The variant SimnetEvent::ErroLog is likely intended to be ErrorLog. This small naming mismatch can be confusing and deviates from typical naming conventions.

Comment on lines 45 to +46
let epoch_info = rpc_client.get_epoch_info().unwrap();
let _ = simnet_events_tx.send(SimnetEvent::EpochInfoUpdate(epoch_info.clone()));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid unwrap() to prevent panics on epoch info retrieval.
Calling rpc_client.get_epoch_info().unwrap() will panic on failure. Consider handling the Result to gracefully recover or report a more controlled error.

-let epoch_info = rpc_client.get_epoch_info().unwrap();
+let epoch_info = match rpc_client.get_epoch_info() {
+    Ok(info) => info,
+    Err(e) => return Err(format!("Failed to get epoch info: {}", e).into()),
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let epoch_info = rpc_client.get_epoch_info().unwrap();
let _ = simnet_events_tx.send(SimnetEvent::EpochInfoUpdate(epoch_info.clone()));
let epoch_info = match rpc_client.get_epoch_info() {
Ok(info) => info,
Err(e) => return Err(format!("Failed to get epoch info: {}", e).into()),
};
let _ = simnet_events_tx.send(SimnetEvent::EpochInfoUpdate(epoch_info.clone()));

Comment on lines 26 to 36
pub enum SimnetEvent {
ClockUpdate(Clock),
EpochInfoUpdate(EpochInfo),
BlockHashExpired,
InfoLog(DateTime<Local>, String),
ErroLog(DateTime<Local>, String),
WarnLog(DateTime<Local>, String),
DebugLog(DateTime<Local>, String),
TransactionReceived(DateTime<Local>, VersionedTransaction),
AccountUpdate(DateTime<Local>, Pubkey),
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use consistent naming for error logging.
The ErroLog variant name is potentially a typo. Rename it to ErrorLog to align with conventional naming:

-pub enum SimnetEvent {
+pub enum SimnetEvent {
     ClockUpdate(Clock),
     EpochInfoUpdate(EpochInfo),
     BlockHashExpired,
-    InfoLog(DateTime<Local>, String),
-    ErroLog(DateTime<Local>, String),
+    InfoLog(DateTime<Local>, String),
+    ErrorLog(DateTime<Local>, String),
     WarnLog(DateTime<Local>, String),
     DebugLog(DateTime<Local>, String),
     TransactionReceived(DateTime<Local>, VersionedTransaction),
     AccountUpdate(DateTime<Local>, Pubkey),
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub enum SimnetEvent {
ClockUpdate(Clock),
EpochInfoUpdate(EpochInfo),
BlockHashExpired,
InfoLog(DateTime<Local>, String),
ErroLog(DateTime<Local>, String),
WarnLog(DateTime<Local>, String),
DebugLog(DateTime<Local>, String),
TransactionReceived(DateTime<Local>, VersionedTransaction),
AccountUpdate(DateTime<Local>, Pubkey),
}
pub enum SimnetEvent {
ClockUpdate(Clock),
EpochInfoUpdate(EpochInfo),
BlockHashExpired,
InfoLog(DateTime<Local>, String),
ErrorLog(DateTime<Local>, String),
WarnLog(DateTime<Local>, String),
DebugLog(DateTime<Local>, String),
TransactionReceived(DateTime<Local>, VersionedTransaction),
AccountUpdate(DateTime<Local>, Pubkey),
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (8)
crates/cli/src/tui/simnet.rs (3)

24-35: Consider supporting multiple theme variations or external configuration.
Currently, the ColorTheme struct is hard-coded to a specific palette (tailwind::EMERALD). If theming becomes more advanced in the future or if users request color customization, you might consider allowing a parameter or a configuration-driven approach to handle multiple themes.


234-234: Avoid calling app.set_colors() on every render.
app.set_colors() is invoked on every UI render loop, but it only reassigns a static color palette. Consider moving it to the initialization phase, or call it only when the user actually changes the theme.

- app.set_colors();
+ // Only call app.set_colors() if theming is toggled or changed at runtime

304-320: Potential performance overhead in render_slots.
For large terminal dimensions, generating and concatenating a big string of / characters might be expensive. Though acceptable for smaller screens, consider short-circuiting or limiting the output if performance becomes an issue for extremely large terminals.

crates/cli/src/cli/simnet/mod.rs (2)

16-18: Avoid hard process exit.
std::process::exit(1) bypasses typical cleanup, dropping, and unwinding. If feasible, consider returning an error instead and letting upstream logic handle it gracefully.


37-75: Consider a mechanism to stop logging gracefully.
log_events loops until the channel is closed, which can be fine, but in situations where the simulator needs to stop early or the user cancels, some interruption mechanism may be desirable.

crates/cli/src/cli/mod.rs (2)

73-77: Ensure consistent naming of flags and clarity in help text.
The flags no-tui and debug are straightforward, but consider clarifying them in the help text:

  • --no-tui: "Use plain logs instead of the TUI dashboard."
  • --debug: "Enable debug-level logs."
    This can improve usability for new users.

117-125: Enhance user guidance for generated completion scripts.
In addition to printing the file name, you could provide an explicit shell command snippet or link to the official docs for each shell so users can quickly enable completions.

crates/core/src/simnet/mod.rs (1)

86-117: Refactor transaction processing into a separate function.

The transaction processing logic is complex and could benefit from being moved into a dedicated function for better maintainability.

+fn process_transaction(
+    tx: VersionedTransaction,
+    ctx: &mut GlobalState,
+    rpc_client: &RpcClient,
+    simnet_events_tx: &Sender<SimnetEvent>,
+) {
+    tx.verify_with_results();
+    let tx = tx.into_legacy_transaction().unwrap();
+    let message = &tx.message;
+    
+    for instruction in &message.instructions {
+        if instruction.program_id_index as usize >= message.account_keys.len() {
+            unreachable!();
+        }
+        let program_id = &message.account_keys[instruction.program_id_index as usize];
+        if ctx.svm.get_account(&program_id).is_none() {
+            let res = rpc_client.get_account(&program_id);
+            let event = match res {
+                Ok(account) => {
+                    let _ = ctx.svm.set_account(*program_id, account);
+                    SimnetEvent::AccountUpdate(Local::now(), program_id.clone())
+                }
+                Err(e) => SimnetEvent::ErroLog(
+                    Local::now(),
+                    format!("unable to retrieve account: {}", e),
+                ),
+            };
+            if let Err(e) = simnet_events_tx.send(event) {
+                eprintln!("Failed to send account event: {}", e);
+            }
+        }
+    }
+    let res = ctx.svm.send_transaction(tx);
+}

Then use it in the main loop:

 while let Ok(tx) = mempool_rx.try_recv() {
-    // ... existing transaction processing code ...
+    process_transaction(tx, &mut ctx, &rpc_client, &simnet_events_tx);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7df4db and a17a31d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • crates/cli/Cargo.toml (1 hunks)
  • crates/cli/src/cli/mod.rs (5 hunks)
  • crates/cli/src/cli/simnet/mod.rs (1 hunks)
  • crates/cli/src/tui/simnet.rs (1 hunks)
  • crates/core/src/rpc/minimal.rs (1 hunks)
  • crates/core/src/simnet/mod.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/core/src/rpc/minimal.rs
  • crates/cli/Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
crates/cli/src/tui/simnet.rs (1)

62-71: Potential unbounded event queue growth.
Storing events in an always-growing VecDeque<(EventType, DateTime<Local>, String)> without a retention policy can eventually lead to high memory usage. Consider a maximum capacity or expiration strategy (e.g., discarding the oldest events).

crates/cli/src/cli/simnet/mod.rs (1)

56-57: Use consistent naming for the variant.
This repeats a past review comment about the ErroLog variant spelling. If you decide to rectify it, rename ErroLog to ErrorLog to align with typical naming conventions.

crates/core/src/simnet/mod.rs (3)

18-18: Verify impact of reduced slot time.

The DEFAULT_SLOT_TIME has been reduced from 2000ms to 400ms, which could significantly increase CPU usage and affect simulation fidelity.

Please ensure this change:

  1. Doesn't overwhelm system resources
  2. Maintains accurate simulation behavior
  3. Aligns with real network timing requirements

26-36: Use consistent naming for error logging.

The ErroLog variant name appears to be a typo and should be renamed to ErrorLog to maintain consistent naming conventions.


45-45: Avoid unwrap() to prevent panics on epoch info retrieval.

Using unwrap() on the RPC client call could cause panics. Consider proper error handling instead.


fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
loop {
while let Ok(event) = app.simnet_events_rx.try_recv() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Investigation Outcome: TUI Shutdown Behavior

The grep results confirm that in the TUI code the event channel is polled via a non‐blocking call (try_recv()) in a loop. This loop continuously processes available events, which raises the concern noted: if new events keep arriving, the loop would keep processing them without an obvious opportunity for an orderly shutdown unless an explicit exit condition (or closed channel) is reached.

Points to Note:

  • The channel is created in crates/cli/src/cli/simnet/mod.rs and passed to the TUI (in crates/cli/src/tui/simnet.rs).
  • In the TUI, the code uses while let Ok(event) = app.simnet_events_rx.try_recv() to pull events.
  • There is no evidence in this snippet that the TUI loop also checks for an external shutdown signal (e.g., a user input or a flag) before continuing to process events.

It is therefore advisable to verify that the design includes another mechanism—such as an external exit signal—to break out of the event-pumping loop. If not, continuous event input will indeed prevent graceful shutdown.

🔗 Analysis chain

Ensure channel activity doesn't block gracefully shutting down the TUI.
try_recv() is a non-blocking call, but if there are continuous events, the TUI loop will keep running indefinitely unless the channel is closed or some external exit signal is provided. Verify that this behavior matches the desired application flow.

You can investigate references to this simnet_events_rx usage across the repository to confirm no unintentional indefinite blocking:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for simnet_events_rx references throughout the repo
rg -A 5 "simnet_events_rx"

Length of output: 4163

Comment on lines +87 to +89
let _ =
simnet_events_tx.send(SimnetEvent::TransactionReceived(Local::now(), tx.clone()));

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle event sending errors appropriately.

Event sending errors are currently ignored with let _. Consider logging these errors or implementing a retry mechanism.

-let _ = simnet_events_tx.send(SimnetEvent::TransactionReceived(Local::now(), tx.clone()));
+if let Err(e) = simnet_events_tx.send(SimnetEvent::TransactionReceived(Local::now(), tx.clone())) {
+    eprintln!("Failed to send transaction event: {}", e);
+}

Also applies to: 132-132

.cors(DomainsValidation::Disabled)
.start_http(&"127.0.0.1:8899".parse().unwrap())
.expect("Unable to start RPC server");
.start_http(&"127.0.0.1:8899".parse().unwrap());
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle address parsing errors gracefully.

Using unwrap() on address parsing could cause panics. Consider proper error handling:

-"127.0.0.1:8899".parse().unwrap()
+match "127.0.0.1:8899".parse() {
+    Ok(addr) => addr,
+    Err(e) => {
+        eprintln!("Failed to parse server address: {}", e);
+        std::process::exit(1);
+    }
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.start_http(&"127.0.0.1:8899".parse().unwrap());
.start_http(&match "127.0.0.1:8899".parse() {
Ok(addr) => addr,
Err(e) => {
eprintln!("Failed to parse server address: {}", e);
std::process::exit(1);
}
});

@lgalabru lgalabru merged commit 47469c1 into main Feb 2, 2025
2 checks passed
@lgalabru lgalabru deleted the feat/tui branch February 2, 2025 06:02
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Nitpick comments (4)
crates/cli/src/cli/simnet/mod.rs (1)

8-30: Improve error handling with more context.

The error handling could be enhanced by providing more context about the failure points:

Apply this diff to improve error handling:

-        .map_err(|e| format!("{}", e))?;
+        .map_err(|e| format!("Failed to spawn simnet thread: {}", e))?;

-    handle.join().map_err(|_e| format!("unable to terminate"))?
+    handle.join().map_err(|e| format!("Failed to join simnet thread: {:?}", e))?
crates/cli/src/cli/mod.rs (1)

110-115: Remove unnecessary async marker.

The function is marked as async but doesn't use any async operations. The implementation is synchronous.

Apply this diff to remove the async marker:

-async fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
+fn handle_command(opts: Opts, ctx: &Context) -> Result<(), String> {
crates/core/src/simnet/mod.rs (1)

70-73: Handle server startup errors gracefully.

The server startup error handling could be improved by providing more context about the failure.

Apply this diff to improve error handling:

-        let Ok(server) = res else {
-            std::process::exit(1);
-        };
+        let server = res.map_err(|e| {
+            eprintln!("Failed to start server: {}", e);
+            std::process::exit(1);
+        })?;
crates/cli/src/tui/simnet.rs (1)

322-366: Limit event queue size and make column widths configurable.

Consider the following improvements:

  1. Add a maximum size for the event queue to prevent unbounded memory growth.
  2. Make column widths configurable or calculate them based on terminal width.

Apply this diff to limit queue size:

 impl App {
     fn new(simnet_events_rx: Receiver<SimnetEvent>, include_debug_logs: bool) -> App {
+        const MAX_EVENTS: usize = 1000;
         App {
             state: TableState::default().with_selected(0),
             scroll_state: ScrollbarState::new(5 * ITEM_HEIGHT),
             colors: ColorTheme::new(&palette::tailwind::EMERALD),
             simnet_events_rx,
             clock: Clock::default(),
             epoch_info: EpochInfo {
                 epoch: 0,
                 slot_index: 0,
                 slots_in_epoch: 0,
                 absolute_slot: 0,
                 block_height: 0,
                 transaction_count: None,
             },
-            events: VecDeque::new(),
+            events: VecDeque::with_capacity(MAX_EVENTS),
             include_debug_logs,
         }
     }
+
+    fn add_event(&mut self, event_type: EventType, dt: DateTime<Local>, log: String) {
+        self.events.push_front((event_type, dt, log));
+        if self.events.len() > MAX_EVENTS {
+            self.events.pop_back();
+        }
+    }
 }
🛑 Comments failed to post (3)
crates/cli/src/cli/simnet/mod.rs (1)

32-76: 🛠️ Refactor suggestion

Handle logger access safely.

The function uses expect_logger() which could panic at runtime. Consider handling the case where logger is not available.

Apply this diff to handle logger access safely:

-    info!(
-        ctx.expect_logger(),
-        "Surfpool: The best place to train before surfing Solana"
-    );
+    if let Some(logger) = ctx.logger.as_ref() {
+        info!(
+            logger,
+            "Surfpool: The best place to train before surfing Solana"
+        );
+    }

Apply similar changes to other logger usages in the function.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

fn log_events(simnet_events_rx: Receiver<SimnetEvent>, include_debug_logs: bool, ctx: &Context) {
    if let Some(logger) = ctx.logger.as_ref() {
        info!(
            logger,
            "Surfpool: The best place to train before surfing Solana"
        );
    }
    while let Ok(event) = simnet_events_rx.recv() {
        match event {
            SimnetEvent::AccountUpdate(_, account) => {
                info!(
                    ctx.expect_logger(),
                    "Account retrieved from Mainnet {}", account
                );
            }
            SimnetEvent::EpochInfoUpdate(epoch_info) => {
                info!(
                    ctx.expect_logger(),
                    "Connection established. Epoch {}, Slot {}.",
                    epoch_info.epoch,
                    epoch_info.slot_index
                );
            }
            SimnetEvent::ClockUpdate(clock) => {
                info!(ctx.expect_logger(), "Slot #{} ", clock.slot);
            }
            SimnetEvent::ErroLog(_, log) => {
                error!(ctx.expect_logger(), "{} ", log);
            }
            SimnetEvent::InfoLog(_, log) => {
                info!(ctx.expect_logger(), "{} ", log);
            }
            SimnetEvent::WarnLog(_, log) => {
                warn!(ctx.expect_logger(), "{} ", log);
            }
            SimnetEvent::DebugLog(_, log) => {
                if include_debug_logs {
                    debug!(ctx.expect_logger(), "{} ", log);
                }
            }
            SimnetEvent::TransactionReceived(_, _transaction) => {
                info!(ctx.expect_logger(), "Transaction received");
            }
            SimnetEvent::BlockHashExpired => {}
        }
    }
}
crates/cli/src/cli/mod.rs (1)

117-126: ⚠️ Potential issue

Add missing macro import.

The code uses the green! macro but it's not imported.

Add the following import at the top of the file:

+use crate::utils::green;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

use crate::utils::green;

fn generate_completion_helpers(cmd: &Completions) -> Result<(), String> {
    let mut app = Opts::command();
    let file_name = cmd.shell.file_name("surfpool");
    let mut file = File::create(file_name.clone())
        .map_err(|e| format!("unable to create file {}: {}", file_name, e))?;
    clap_complete::generate(cmd.shell, &mut app, "surfpool", &mut file);
    println!("{} {}", green!("Created file"), file_name.clone());
    println!("Check your shell’s docs for how to enable completions for surfpool.");
    Ok(())
}
crates/cli/src/tui/simnet.rs (1)

94-96: 🛠️ Refactor suggestion

Handle slot conversion safely.

Using unwrap() on the conversion could cause panics if the slot value doesn't fit in usize.

Apply this diff to handle the conversion safely:

-    pub fn slot(&self) -> usize {
-        self.clock.slot.try_into().unwrap()
+    pub fn slot(&self) -> usize {
+        self.clock.slot.try_into().unwrap_or(0)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    pub fn slot(&self) -> usize {
        self.clock.slot.try_into().unwrap_or(0)
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant